package com.cjst.controller.image;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cjst.controller.base.BaseController;
import com.cjst.pojo.base.AlarmResult;
import com.cjst.pojo.sys.SysUser;
import com.cjst.service.base.AlarmResultService;
import com.cjst.service.dubbo.BroadCastDubboService;
import com.cjst.service.dubbo.HkDubboService;
import com.cjst.service.intelligent.IntelligentControlService;
import com.cjst.service.part.PartConnectionParametersService;
import com.cjst.service.redis.RedisService;
import com.cjst.service.sys.SysUserService;
import com.cjst.util.FileToByte;
import com.cjst.util.MyMap;
import com.cjst.util.SendSmsUtil;
import com.cjst.util.common.DateUtil;
import com.cjst.util.common.ResultCode;
import com.cjst.util.json.ResultObj;
import com.itextpdf.text.log.SysoCounter;

@Controller
@RequestMapping("/image")
public class ImageController extends BaseController{
	private static final Logger log = Logger.getLogger(ImageController.class);
	@Reference
	private HkDubboService hkDubboService;
	@Autowired
	private SendSmsUtil sendSmsUtil;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private RedisService redisService;
	@Autowired
	private AlarmResultService alarmResultService;			//报警记录
	@Autowired
	private PartConnectionParametersService parametersService;			//智能设备参数 
	@Reference
	private BroadCastDubboService broadCastDubboService;
	@Value("${img.location}")
	private String uploadDir;
	@Autowired
	private IntelligentControlService intelligentControlService;
	@RequestMapping("/ts")
	@ResponseBody
	public String ts(){
		try{
			Map<String, Object> map=hkDubboService.analyseByMap("0.0.0.0", 8000, "admin", "chengjist123456");
	    	if(map!=null){
				//Float score=(Float) map.get("score");
				String type=(String) map.get("type");
				int code=(int) map.get("code");
				List<SysUser> sysList=sysUserService.list(null);				//后面根据实际设备得到值
				Map<String, Object> templateParamMap=new HashMap<String, Object>();
				templateParamMap.put("code", 1);
				AlarmResult ar=new AlarmResult();
				ar.setType(1);   				//自动触发
				ar.setPartId("1");
				String content="";
				if(code==1){				//设备异常
					Object obj=redisService.getObj("sbsss"+1);
					if(obj==null || obj.equals(null)){
						content="设备故障或关机";
						templateParamMap.put("content", content);
						ar.setAlarmExplain("1号设备设备故障或关机");
						if(sysList!=null && sysList.size()>0){ 
							for (SysUser sysUser : sysList) { 
								sendSmsUtil.sendSms(sysUser.getPhone(), "SMS_177360063", templateParamMap, "", null, "植城智慧", "设备故障");
							}
							ar.setAlarmType("设备故障");
							MyMap.getMyMap().put2("broadcast_"+1+DateUtil.dateToString(new Date()), "1号摄像头故障，请到现场查看");
							alarmResultService.addLocalByid(ar);
						}
						
						redisService.setObjByTime("sbsss"+1, 1, 24*60*60);
					}
				}else{
					int bz=0;
					int flag=(int) map.get("flag");
					log.info("=========type"+type);
						
					if(flag==0){					//不文明行为
						templateParamMap.put("content", "有疑似"+type+"人");
						if(sysList!=null && sysList.size()>0){
							for (SysUser sysUser : sysList) {
								sendSmsUtil.sendSms(sysUser.getPhone(), "SMS_177360063", templateParamMap, "", null, "植城智慧", "视频报警");
							}
						}
						String yy= "发现"+type+"者,为了园区的良好的环境，请不要"+type+"请不要"+type;
						ar.setAlarmExplain(yy);
						//MyMap.getMyMap().put2("broadcast_"+1+DateUtil.dateToString(new Date()), "发现"+type+"者,为了园区的良好的环境，请不要"+type+"请不要"+type);
						broadCastDubboService.skPlay(1, 1, yy, "1", 1);			//播放
						bz=1;
					}else if(flag==1){			//动物
						templateParamMap.put("content", "有疑似携带"+type+"的人");
						String yy="发现有携带宠物"+type+"入园，为了园区的良好环境，请不要携带宠物"+type+"入园";
						if(sysList!=null && sysList.size()>0){
							for (SysUser sysUser : sysList) {
								sendSmsUtil.sendSms(sysUser.getPhone(), "SMS_177360063", templateParamMap, "", null, "植城智慧", "视频报警");
							}
						}
						ar.setAlarmExplain(yy);
						//MyMap.getMyMap().put2("broadcast_"+1+DateUtil.dateToString(new Date()), "发现有携带宠物"+type+"入园，为了园区的良好环境，请不要携带宠物"+type+"入园");
						broadCastDubboService.skPlay(1, 1, yy, "1", 1);			//播放
						bz=1;
					}
					
					if(bz==1){
						byte[] img64=(byte[]) map.get("img");
						//byte[] img64=strImg64.getBytes();
						String imgUrl="/alarm/"+"1/"+DateUtil.dateToString(new Date(),"yyyyMMddHHmmss")+".jpg";
						FileToByte.byte2image(img64, uploadDir+imgUrl);
						ar.setImgUrl(imgUrl);
						ar.setIsBroadcast(1);
						ar.setAlarmType("视频报警");
						ar.setFback("1");
						//ar.setCreateTime(DateUtil.stringToDate(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
						alarmResultService.addLocalByid(ar);
					}
				}
					
	    	}else{
				log.info("=========未发现异常");
			}
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "识别完成",null);
			return robj.toString();
		}catch(Exception e){
			e.printStackTrace();
			ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "参数错误",null);
			return robj.toString();
		}
	}
	@RequestMapping("/imageDiscern")
	@ResponseBody
	public String imageDiscern(MultipartFile file,Integer type){
		try{
			if(type==null){
				type=0;
			}
			//文件名称
            String fileName = file.getOriginalFilename();
            //文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            uploadDir = uploadDir + "/" + "baiduMind" + "/" + "image";
            //检查目录是否存在
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //随机名称
            String randomFileName = UUID.randomUUID().toString();
            //文件存在服务器上的路径
            String fileUrl = uploadDir + "/" + randomFileName + "." + suffix;
            //将文件上传到文集的物理地址
            File serverFile = new File(fileUrl);
            file.transferTo(serverFile);
            Map<String, Object> map=intelligentControlService.imageControl(fileUrl, 0);
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "识别完成",map);
			return robj.toString();
		}catch(Exception e){
			e.printStackTrace();
			ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "参数错误",null);
			return robj.toString();
		}
	}
	@RequestMapping(value = "/upImage", method = RequestMethod.POST)
	@ResponseBody
    public String upImage(MultipartFile file) {
		try{
			//System.out.println("================uploadDir1sss:"+uploadDir);
			//文件名称
			String fileName = file.getOriginalFilename();
			//System.out.println("================uploadDir1:"+uploadDir);
			log.info("================uploadDir1:"+uploadDir);
        	//文件后缀
        	String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        	uploadDir = uploadDir + "/" + "baidus";
        	log.info("================uploadDir2:"+uploadDir);
        	//检查目录是否存在
        	File dir = new File(uploadDir);
        	if (!dir.exists()) {
            	dir.mkdirs();
        	}
        	//随机名称
        	String randomFileName = UUID.randomUUID().toString();
        	//文件存在服务器上的路径
        	String  fileUrl= uploadDir + "/" + randomFileName + "." + suffix;
        	String fileUrl2 = uploadDir + "/ys_" + randomFileName + "." + suffix;
        	//将文件上传到文集的物理地址
        	File serverFile = new File(fileUrl);
        	file.transferTo(serverFile);
        	//图片压缩
        	FileToByte.commpressPicForScale(fileUrl, fileUrl2);
        	/*Thumbnails.of(fileUrl) 
            .scale(1f) 
            .outputQuality(0.5f) 
            .toFile(fileUrl2);*/
        	ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "识别完成",fileUrl2);
        	uploadDir="";
			return robj.toString(); 
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
    }
	@RequestMapping(value = "/imageSb", method = RequestMethod.POST)
	@ResponseBody
    public String imageSb(String fileDir,Integer type,Integer isBroad,String phone) {
		try{
			if(fileDir==null || fileDir.length()==0){
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "参数错误",null);
				return robj.toString();
			}
			if(isBroad==null){
				isBroad=0;
			}
			if(type==null){
				type=0;
			}
			Map<String, Object> map=intelligentControlService.imageControl(fileDir, 0);
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "识别完成",map);
			return robj.toString();
		}catch(Exception e){
			e.printStackTrace();
			ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "参数错误",null);
			return robj.toString();
		}
    }
	@RequestMapping(value = "", method = RequestMethod.GET)
    public String toImage() {
        return "image";
    }
	@RequestMapping(value = "/deedImg", method = RequestMethod.POST)
	@ResponseBody
    public String deedImg(MultipartFile file) {
		try{
			//文件名称
            String fileName = file.getOriginalFilename();
            //文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            uploadDir = uploadDir + "/" + "tx" ;
            //检查目录是否存在
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //随机名称
            String randomFileName = UUID.randomUUID().toString();
            //文件存在服务器上的路径
            String fileUrl = uploadDir + "/" + randomFileName + "." + suffix;
            String fileUrl2 = uploadDir + "/ys_" + randomFileName + "." + suffix;
            //将文件上传到文集的物理地址
            File serverFile = new File(fileUrl);
            file.transferTo(serverFile);
            //图片压缩
        	FileToByte.commpressPicForScale(fileUrl, fileUrl2);
			Map<String, Object> map=intelligentControlService.deedImg(FileToByte.readFile(fileUrl2));
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "识别完成",map);
			uploadDir="";
			return robj.toString();
		}catch(Exception e){
			e.printStackTrace();
			ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "参数错误",null);
			return robj.toString();
		}
	}
}



